package com.kob.backend.consumer;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kob.backend.consumer.utils.FriendGame;
import com.kob.backend.consumer.utils.Game;
import com.kob.backend.consumer.utils.JwtAuthentication;
import com.kob.backend.mapper.BotMapper;
import com.kob.backend.mapper.MsgMapper;
import com.kob.backend.mapper.RecordMapper;
import com.kob.backend.mapper.UserMapper;
import com.kob.backend.pojo.Bot;
import com.kob.backend.pojo.Msg;
import com.kob.backend.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
@ServerEndpoint("/websocket/{token}")  // 注意不要以'/'结尾
public class WebSocketServer {

    public final static ConcurrentHashMap<Integer,WebSocketServer> users = new ConcurrentHashMap<>();
    private User user;
    private Session session;
    public static UserMapper userMapper;
    public static RecordMapper recordMapper;
    public static RestTemplate restTemplate;
    private static BotMapper botMapper;
    private static MsgMapper msgMapper;
    public Game game = null;
    public FriendGame fGame = null;
    private final static String addPlayerURL = "http://127.0.0.1:3001/player/add/";
    private final static String removePlayerURL = "http://127.0.0.1:3001/player/remove/";

    @Autowired
    public void setMsgMapper(MsgMapper msgMapper){
        WebSocketServer.msgMapper = msgMapper;
    }
    @Autowired
    public void setUserMapper(UserMapper userMapper){
        WebSocketServer.userMapper = userMapper;
    }

    @Autowired
    public void setRecordMapper(RecordMapper recordMapper) {
        WebSocketServer.recordMapper = recordMapper;
    }

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate){
        WebSocketServer.restTemplate = restTemplate;
    }

    @Autowired
    public void setBotMapper(BotMapper botMapper){
        WebSocketServer.botMapper = botMapper;
    }
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) throws IOException {
        // 建立连接
        this.session = session;
        Integer userId = JwtAuthentication.getUserId(token);
        this.user = userMapper.selectById(userId);

        if(user != null){
            users.put(userId,this);
        }else{
            this.session.close();
        }

    }

    @OnClose
    public void onClose() {
        // 关闭链接
        if(this.user!=null){
            users.remove(this.user.getId());
        }
    }
    public void startLocalGame(boolean isPVA){
        User usera = this.user;
        FriendGame fGame = new FriendGame(13,14,20,usera.getId(),isPVA);
        fGame.creatMap();
        if(users.get(usera.getId())!=null){
            users.get(usera.getId()).fGame=fGame;
        }
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.submit(fGame);
        //fGame.start();
        JSONObject respGame = new JSONObject();
        respGame.put("map",fGame.getG());
        JSONObject resp = new JSONObject();
        resp.put("event","startFG");
        respGame.put("a_id",fGame.getPlayerA().getId());
        respGame.put("a_sx",fGame.getPlayerA().getSx());
        respGame.put("a_sy",fGame.getPlayerA().getSy());
        respGame.put("b_id",fGame.getPlayerB().getId());
        respGame.put("b_sx",fGame.getPlayerB().getSx());
        respGame.put("b_sy",fGame.getPlayerB().getSy());
        resp.put("game",respGame);
        if(users.get(usera.getId())!=null){
            users.get(usera.getId()).sendMseeage(resp.toJSONString());
        }
    }
    public static void startGame(Integer aId,Integer aBotId, Integer bId, Integer bBotId){
        User a = userMapper.selectById(aId);
        User b = userMapper.selectById(bId);
        Bot botA = botMapper.selectById(aBotId);
        Bot botB = botMapper.selectById(bBotId);
        Game game = new Game(13,14,20,a.getId(),botA,b.getId(),botB);
        game.creatMap();
        if(users.get(a.getId())!=null){
            users.get(a.getId()).game = game;
        }
        if(users.get(b.getId())!=null){
            users.get(b.getId()).game = game;
        }
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.submit(game);
        //game.start();
        JSONObject respGame = new JSONObject();
        respGame.put("a_id",game.getPlayerA().getId());
        respGame.put("a_sx",game.getPlayerA().getSx());
        respGame.put("a_sy",game.getPlayerA().getSy());
        respGame.put("b_id",game.getPlayerB().getId());
        respGame.put("b_sx",game.getPlayerB().getSx());
        respGame.put("b_sy",game.getPlayerB().getSy());
        respGame.put("map",game.getG());
        JSONObject respA = new JSONObject();
        respA.put("event","startMatching");
        respA.put("opponent_username",b.getUsername());
        respA.put("opponent_photo",b.getPhoto());
        respA.put("game",respGame);
        if(users.get(a.getId())!=null){
            users.get(a.getId()).sendMseeage(respA.toJSONString());
        }
        JSONObject respB = new JSONObject();
        respB.put("event","startMatching");
        respB.put("opponent_username",a.getUsername());
        respB.put("opponent_photo",a.getPhoto());
        respB.put("game",respGame);
        if(users.get(b.getId())!=null){
            users.get(b.getId()).sendMseeage(respB.toJSONString());
        }
    }
    private void startMatching(Integer botId){
        MultiValueMap<String, String> data = new LinkedMultiValueMap<>();
        data.add("user_id",this.user.getId().toString());
        data.add("rating",this.user.getRating().toString());
        data.add("bot_id",botId.toString());
        restTemplate.postForObject(addPlayerURL,data, String.class);
    }
    private void stopMatching(){
        MultiValueMap<String, String> data = new LinkedMultiValueMap<>();
        data.add("user_id",this.user.getId().toString());
        restTemplate.postForObject(removePlayerURL,data, String.class);
    }

    private void move(int direction){
        if(game!=null){
            if(game.getPlayerA().getId().equals(user.getId())){
                if(game.getPlayerA().getBotId().equals(-1)) { //人工操作
                    game.setNextStepA(direction);
                }
            }else if(game.getPlayerB().getId().equals(user.getId())){
                if(game.getPlayerB().getBotId().equals(-1)){
                    game.setNextStepB(direction);
                }
            }
        }
    }
    private void move_f1(int direction){
        if(fGame!=null){
            fGame.setNextStepA(direction);
        }
    }
    private void move_f2(int direction){
        if(fGame!=null){
            //if(fGame.getDifficulty() == 0){ //人人对战
                fGame.setNextStepB(direction);
           // }
        }
    }
    private void return_msg(){
        JSONObject sendmsg = new JSONObject();
        QueryWrapper<Msg> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
            List<Msg> list = msgMapper.selectList(queryWrapper);
            if(list != null){
                sendmsg.put("event","msgs");
                sendmsg.put("msgs",list);
                users.forEach((key,value)->{
                    value.sendMseeage(sendmsg.toJSONString());
                });
            }
    }
    private void sendmsg(String message){
        Msg msg = new Msg(null,message,user.getId(),new Date(),user.getUsername());
        msgMapper.insert(msg);
    }
    @OnMessage
    public void onMessage(String message, Session session) {
        // 从Client接收消息
        JSONObject data = JSONObject.parseObject(message);
        String event = data.getString("event");
        if("start-matching".equals(event)){
            startMatching(data.getInteger("bot_id"));
        }else if("stop-matching".equals(event)){
            stopMatching();
        }else if("move".equals(event)){
            move(data.getInteger("direction"));
        }else if("send_msg".equals(event)){
            sendmsg(data.getString("msg"));
        }else if("receive_msg".equals(event)){
            return_msg();
        }else if("start_friend_game".equals(event)){
            startLocalGame(false);
        }else if("move_f1".equals(event)){
            move_f1(data.getInteger("direction"));
        }else if("move_f2".equals(event)){
            move_f2(data.getInteger("direction"));
        }else if("start_PVA".equals(event)){
            startLocalGame(true);
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    public void sendMseeage(String message){
        synchronized (this.session){
            try{
                this.session.getBasicRemote().sendText(message);
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}
